import json
import pandas as pd
import argparse
from pathlib import Path


def read_jsonl(jsonl_path):
    """读取 jsonl 文件为 list[dict]"""
    data = []
    with open(jsonl_path, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            try:
                data.append(json.loads(line))
            except json.JSONDecodeError as e:
                print(f"⚠️ JSON decode error: {e}\nLine: {line[:100]}")
    return data


def merge_result_with_gt(result_data, gt_df, jsonl_path):
    """根据 case_id / 需求编号 Requirement ID 合并（仅匹配 测试等级=冒烟，可一对多合并）"""
    merged_data = []

    # 先过滤出“测试等级 Test Level”为“冒烟”的条目
    gt_df = gt_df[gt_df["测试等级\nTest Level"].astype(str).str.strip() == "冒烟"]

     # ✅ 读取 jsonl 文件
    jsonl_map = {}
    with open(jsonl_path, "r", encoding="utf-8") as f:
        for line in f:
            entry = json.loads(line)
            case_id = str(entry.get("case_id", "")).strip()
            if case_id:
                jsonl_map[case_id] = entry

    for item in result_data:
        case_id = item.get("case_id", "").strip()
        matched = gt_df[gt_df["需求编号\nRequirement ID"].astype(str).str.strip() == case_id]

        if not matched.empty:
            # 多条时合并（使用“；”连接）
            item["gt_前置条件"] = "；".join(matched["前置条件\nPreconditions"].astype(str))
            item["gt_操作步骤"] = "；".join(matched["操作步骤\nOperate Step"].astype(str))
            item["gt_预期结果"] = "；".join(matched["预期结果\nExpected results"].astype(str))

         # === 合并 JSONL 中除 pin_mappings 外的内容 ===
        if case_id in jsonl_map:
            extra_data = {k: v for k, v in jsonl_map[case_id].items() if k != "pin_mappings"}
            item.update(extra_data)
        merged_data.append(item)

    return merged_data



def export_to_csv(merged_data, output_path, columns_order=None):
    """导出为 CSV，可调整表头顺序"""
    df = pd.DataFrame(merged_data)

    if columns_order:
        # 保留指定顺序的列，其余列附在后面
        ordered_cols = [c for c in columns_order if c in df.columns]
        remaining_cols = [c for c in df.columns if c not in ordered_cols]
        df = df[ordered_cols + remaining_cols]

    df.to_csv(output_path, index=False, encoding='utf-8-sig')
    print(f"✅ 已导出: {output_path}")


def main():

    result_data = read_jsonl('/Users/yangchen/Desktop/car_ut/aaa_rag/all_results_1102_0125_qwen3-32b.jsonl')
    gt_df = pd.read_excel('/Users/yangchen/Desktop/HIL测试用例生成/003 G393_BDC_EW01_雨刮洗涤系统功能测试报告V2.xlsx', sheet_name=2)
    merged_data = merge_result_with_gt(result_data, gt_df, './all_cases.jsonl')
    export_to_csv(merged_data, '/Users/yangchen/Desktop/car_ut/aaa_rag/merged_result.csv', None)

    # import pandas as pd
    # df = pd.read_excel("/Users/st/Desktop/case/003 G393_BDC_EW01_雨刮洗涤系统功能测试报告V2.xlsx", sheet_name=2)
    # print(df.columns.tolist())


if __name__ == "__main__":
    main()
